const Service = require('egg').Service;

var uuid = require('uuid');

class ApiService extends Service {

	async list (sqljson, para) {

		let sql = ' select ';

		let col = '';
		sqljson.col.forEach(item => {
			col += item.tname + '.' + item.cname;
			if(item.asname != '') col += ' as ' + item.asname;
			col += ' ,';
		})

        col = col.replace(/,$/gi,"");

		let table = ' from ' + sqljson.table.master;
		sqljson.table.condition.forEach(item => {
			table += item.what + item.table + ' on ' + 
			sqljson.table.master + '.' + item.on[0] + ' = ' +
			item.table + '.' + item.on[1] + ' ';
		});

		let where = ' where ';
		let count = 0;

		let arr = [];
		sqljson.where.forEach((item, index) => {
			const { tname, cname, what, value, condition } = item;
			if(value != '?' || para[cname] != undefined){
				if(count != 0) where += condition;
				where += tname + '.' + cname + what + value;

				if(what == ' like '){
					arr.push('%' + para[cname] + '%');
				}else{
					arr.push(para[cname]);
				}
				
				count++;
			}
		});

		let s = sql + col + table;

		if(count > 0) s += where;

		console.log(count);
		console.log('-==================')
		console.log(s);

		const result = await this.app.mysql.get(sqljson.database).query(s, arr);
		return result;
	}

	async info (sqljson, id) {

		let sql = ' select ';

		let col = '';
		sqljson.col.forEach(item => {
			col += item.tname + '.' + item.cname;
			if(item.asname != '') col += ' as ' + item.asname;
			col += ' ,';
		})

        col = col.replace(/,$/gi,"");

		let table = ' from ' + sqljson.table.master;
		sqljson.table.condition.forEach(item => {
			table += item.what + item.table + ' on ' + 
			sqljson.table.master + '.' + item.on[0] + ' = ' +
			item.table + '.' + item.on[1] + ' ';
		});

		const where = ' where ' + sqljson.infoWhere.tname + '.' + sqljson.infoWhere.cname + ' =?'

		const s = sql + col + table + where;

		console.log('-==================')
		console.log(s);
		console.log(id);

		const result = await this.app.mysql.get(sqljson.database).query(s, id);
		return result[0];
	}

	async update (para, sqljson) {
		let result = null;

		const conn = this.app.mysql.get(sqljson.database);

		const { id } = para;

		if(id != undefined){

			delete para.create_time;
			delete para.update_time;

			result = await conn.update(sqljson.table.master, {
				...para,
				update_time : conn.literals.now,
			});
		}else{
			result = await conn.insert(sqljson.table.master, {
				id : uuid.v1(),
				...para,
				create_time : conn.literals.now,
				update_time : conn.literals.now,
			});
		}

		return result.affectedRows === 1;
	}
}

module.exports = ApiService;